//
//  SearchViewController.m
//  cm
//
//  Created by suyibaishan on 2017/11/10.
//  Copyright © 2017年 feihu. All rights reserved.
//

#import "SearchViewController.h"
#import "CollectionViewCell.h"
#import "GoodsViewController.h"

@interface SearchViewController () <UICollectionViewDelegate,UICollectionViewDataSource,UITextFieldDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) UITextField *searchField;

@end

@implementation SearchViewController
{
    MBProgressHUD *HUD;
    NSInteger page;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self createSearchView];
}

-(void)createSearchView
{
    self.view.backgroundColor = [UIColor whiteColor];
    
    _searchField = ({
        UIImageView *leftImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"search"]];
        leftImage.contentMode = UIViewContentModeScaleAspectFit;
//        leftImage.frame = CGRectMake(0, 0, 20, 20);
        
        UITextField *tfield = [UITextField new];
        tfield.textAlignment = NSTextAlignmentCenter;
        [self.baseBar addSubview:tfield];
        tfield.rightView = leftImage;
        tfield.rightViewMode = UITextFieldViewModeAlways;
        [tfield.layer setCornerRadius:5.0];
        tfield.returnKeyType = UIReturnKeySearch;
        [tfield setFont:[UIFont systemFontOfSize:14]];
        tfield.clearButtonMode = UITextFieldViewModeAlways;
        tfield.backgroundColor = [UIColor colorWithRed:0.91 green:0.93 blue:0.93 alpha:1];
        tfield.textColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:1];
        UIColor *color = [UIColor colorWithRed:0.7 green:0.7 blue:0.7 alpha:1];
        tfield.attributedPlaceholder = [[NSAttributedString alloc] initWithString:@"请输入关键字搜索" attributes:@{NSForegroundColorAttributeName: color}];
        tfield;
    });
    _searchField.delegate = self;
//    [_searchField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    _searchField.sd_layout
    .leftSpaceToView(self.baseBar, 15)
    .topSpaceToView(self.baseBar, statusBarRect.size.height+8)
    .widthIs(kScreenWidth - 70)
    .heightIs(28);
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [cancelBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(backViewController) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:cancelBtn];
    cancelBtn.sd_layout
    .rightSpaceToView(self.view, 5)
    .topSpaceToView(self.view, statusBarRect.size.height)
    .widthIs(44)
    .heightIs(44);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [_searchField becomeFirstResponder];
    });
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.minimumInteritemSpacing = 0.f;
    layout.minimumLineSpacing = 0.5f;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    _collectionView.delegate = self;
    _collectionView.dataSource = self;
    _collectionView.showsVerticalScrollIndicator = NO;
    _collectionView.backgroundColor = [UIColor colorWithRed:0.96 green:0.97 blue:0.97 alpha:1];
    [self.view addSubview:_collectionView];
    _collectionView.sd_layout
    .leftSpaceToView(self.view, 0)
    .topSpaceToView(self.baseBar, 0)
    .widthIs(kScreenWidth)
    .heightIs(kScreenHeight - self.baseBarHeight);
    
    [_collectionView registerClass:[CollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentify"];
    
    _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
//        [self reloadData];
    }];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    _collectionView.mj_header.automaticallyChangeAlpha = YES;
    _collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
//        [self loadMoreData];
    }];
    
    self.dataSource = [NSMutableArray array];
    
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
}

-(void)backViewController
{
    [self.navigationController popViewControllerAnimated:NO];
}

#pragma mark -- UICollectionViewDataSource
//定义展示的UICollectionViewCell的个数
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataSource.count;
}

//定义展示的Section的个数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

//每个UICollectionView展示的内容
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdentifier = @"cellIdentify";
    CollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
    cell.model = [[CollectionModel alloc] initWithDictionary:self.dataSource[indexPath.row]];
    
    return cell;
}

#pragma mark --UICollectionViewDelegateFlowLayout
//定义每个UICollectionView的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((kScreenWidth - 15)/2, (kScreenWidth - 15)/2+70);
}

//定义每个UICollectionView的margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(5, 5, 5, 5);
}

#pragma mark --UICollectionViewDelegate
//UICollectionView被选中时调用的方法
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    GoodsViewController *goodsVC = [[GoodsViewController alloc] init];
    goodsVC.dataSource = self.dataSource[indexPath.row];
    [self.navigationController pushViewController:goodsVC animated:YES];
}

//返回这个UICollectionView是否可以被选择
-(BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

-(void)reloadData:(NSString *)productName
{
    [[ToolNet sharedManager] getCarsList:productName pageNum:1 pageSize:16 url:MCarsList completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        if ([responseJson[@"code"] isEqual:@1]) {
            [self.dataSource removeAllObjects];
            [self.dataSource addObjectsFromArray:responseJson[@"data"][@"list"]];
            [_collectionView reloadData];
            page = 2;
        }
        else {
            [self showMessage:responseJson[@"msg"]];
        }
        [_collectionView.mj_header endRefreshing];
        [_collectionView.mj_footer endRefreshing];
    }];
}

-(void)loadMoreData
{
    [HUD show:YES];
    [[ToolNet sharedManager] getCarsList:nil pageNum:page pageSize:16 url:MCarsList completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        [HUD hide:YES];
        if ([responseJson[@"code"] isEqual:@1]) {
            if ([responseJson[@"data"][@"pages"] integerValue] >= page) {
                [self.dataSource addObjectsFromArray:responseJson[@"data"][@"list"]];
                [_collectionView.mj_footer endRefreshing];
                page++;
            }
            else{
                [_collectionView.mj_footer endRefreshingWithNoMoreData];
            }
            [_collectionView reloadData];
        }
        else {
            [self showMessage:responseJson[@"msg"]];
            [_collectionView.mj_footer endRefreshing];
        }
    }];
}

#pragma mark - UITextFieldDelegate
//- (void)textFieldDidChange:(UITextField *)textField
//{
//    [self reloadData:textField.text];
//}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [self reloadData:textField.text];
    
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
